package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    /**
     * 发送验证码
     * @param phone
     * @param session
     */
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1.验证手机号
        if (RegexUtils.isPhoneInvalid(phone)){
            //2.不符合返回错误信息
            return Result.fail("手机号格式有误");
        }
        //3.符合，生成验证码
        String code = RandomUtil.randomString(6);
        //4.保存验证码到Redis中
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL,TimeUnit.MINUTES);
        //5.返回验证码信息（模拟）
        log.debug("模拟发送验证码成功,{}",code);
        return Result.ok();
    }

    /**
     * 短信验证码登录，注册
     * @param loginForm
     * @param session
     * @return
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        //1.校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("手机号格式有误");
        }
        //2.校验验证码
        Object cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY+phone);
        String code = loginForm.getCode();
        if (cacheCode == null || !cacheCode.toString().equals(code)){
            return Result.fail("验证码输入有误");
        }
        //3.根据手机号查询用户
        User user = query().eq("phone", phone).one();
        //4.判断用户是否存在
        if (user == null){
            //5.如果不存在就进行注册并保存到数据库中
            user = createUserWithPhone(phone);
        }
        //6.保存用户到redis中
        //6.1 生成token作为登录令牌
        String token = UUID.randomUUID().toString(true);
        log.debug("Generated token: {}", token);

        //6.2 将user对象转为hash进行存储
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        log.debug("UserDTO data: {}", userDTO);

        Map<String,Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName,fieldValue) -> fieldValue.toString()));
        //log.debug("Converted userMap: {}", userMap);

//        if (userMap.isEmpty()) {
//            log.error("UserMap is empty after conversion!");
//            return Result.fail("用户数据转换失败");
//        }

        //6.3 存储
        String tokenKey = LOGIN_USER_KEY + token;
        log.debug("Storing data in Redis with key: {}", tokenKey);
        try {
            stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
            //6.4设置有效期
            Boolean success = stringRedisTemplate.expire(tokenKey, LOGIN_USER_TTL, TimeUnit.MINUTES);
            log.debug("Set expiration result: {}", success);
        } catch (Exception e) {
            log.error("Redis operation failed", e);
            return Result.fail("服务器异常，请稍后重试");
        }
        //7.返回token
        return Result.ok(token);
    }

    @Override
    public Result queryUserById(Long userId) {
        User user = getById(userId);
        if (user == null){
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return Result.ok(userDTO);
    }

    /**
     * 用户签到
     * @return
     */
    @Override
    public Result sign() {
        //获取当前用户信息
        Long userId = UserHolder.getUser().getId();
        //获取现在的日期
        LocalDateTime time = LocalDateTime.now();
        //拼接key
        String keySuffix = time.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY + keySuffix;
        //判断今天是这个月的第几天
        int dayOfMonth = time.getDayOfMonth();
        //写入redis
        stringRedisTemplate.opsForValue().setBit(key,dayOfMonth-1,true);
        return Result.ok();
    }
    /**
     * 计算用户连续签到天数
     * @return
     */
    @Override
    public Result SignCount() {
        //先获取本月截止到今天为止的签到记录
        Long userId = UserHolder.getUser().getId();
        LocalDateTime now = LocalDateTime.now();
        //拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        String key = USER_SIGN_KEY+userId+keySuffix;
        //获取今天是这个月的第几天
        int dayOfMonth = now.getDayOfMonth();
        //获取本月截止到今天为止的所有签到记录，BitField key get u[dayOfMonth] 0
        List<Long> bitField = stringRedisTemplate.opsForValue().bitField(
                key, BitFieldSubCommands.create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth))
                        .valueAt(0)
        );
        if (bitField == null || bitField.isEmpty()){
            return Result.ok(0);
        }
        Long num = bitField.get(0);
        if (num == null || num == 0){
            return Result.ok(0);
        }
        //返回的是一个10进制的数字,要想从后往前遍历每个bit位
        //我们需要让1与这个数字进行与运算,用来判断这个数字的最后一个比特位是否为1（是否已签到:0 未签到 1：已签到）
        int count = 0;
        while (true){
            if ((num & 1) == 0){
                //0:说明未签到。直接跳出循环
                break;
            }else {
                //1:已签到：计数器+1
                count++;
            }
            //把这个数字右移一位。抛弃最后一个bit位，继续进行下一个的判断。
            num >>>= 1;
        }
        return Result.ok(count);
    }



    private User createUserWithPhone(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
